#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN DATA ABSTRACTION LAYER version 1

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For commercial software, please obtain a commercial license from THN Solutions LLC.

  + For free software, this library is licensed under GPL version 3. A summary of GPLv3 is
    listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt included
	with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Using directives
using System;
using System.Data;
using System.Collections;
using Thn.Data.Mapping;
using Thn.Data.Exceptions;
using Thn.Data.Settings;
using Thn.Application;
using System.ComponentModel;
#endregion

namespace Thn.Data.Database.Sql.Dialect
{
    /// <summary>
    /// Abstract SQL dialect base
    /// </summary>
    public abstract class AbstractDialect : ISqlDialect
    {
        #region TypeMap
        private Hashtable mTypeMap = null;
        /// <summary>
        /// Caches of .NET type to database specific type
        /// <para>Key   : .NET type</para>
        /// <para>Value : database type</para>
        /// </summary>
        protected Hashtable TypeMap
        {
            get 
            {
                if (mTypeMap == null)
                {
                    //map not exists, create one
                    mTypeMap = new Hashtable();
                    mStringMap = new Hashtable();
                    MapTypes(mTypeMap, mStringMap);
                }
                return mTypeMap; 
            }
        }
        #endregion

        #region StringMap
        private Hashtable mStringMap = null;
        /// <summary>
        /// Caches of .NET type to database specific type as string
        /// <para>Key  : .NET type</para>
        /// <para>Value: database type as string</para>
        /// </summary>
        protected Hashtable StringMap
        {
            get 
            {
                if (mStringMap == null)
                {
                    //map not exists, create one
                    mTypeMap = new Hashtable();
                    mStringMap = new Hashtable();
                    MapTypes(mTypeMap, mStringMap);
                }

                return mStringMap; 
            }
        }
        #endregion

        #region Create Connection
        /// <summary>
        /// Construct a database specific connection instance
        /// </summary>
        public abstract IDbConnection CreateConnection();
        #endregion

        #region Create command
        /// <summary>
        /// Construct a database specific command instance
        /// </summary>
        public abstract IDbCommand CreateCommand();
        #endregion

        #region Create Parameter
        /// <summary>
        /// Construct a database specific parameter instance
        /// </summary>
        /// <param name="paramName">Name of parameter</param>
        /// <param name="valueType">.NET type of parameter's value</param>
        public abstract IDataParameter CreateParameter(string paramName, Type valueType);

        ///// <summary>
        ///// Construct a database specific parameter instance
        ///// </summary>
        ///// <param name="attribute">The attribute mapping</param>
        //public abstract IDataParameter CreateParameter(AttributeMap attribute);
        #endregion

        #region Map Types
        /// <summary>
        /// Maps .NET types to data types.
        /// </summary>
        /// <param name="typeMap">key: .NET type, value: data type</param>
        /// <param name="stringMap">key: .NET type, value: data type as string</param>
        protected abstract void MapTypes(Hashtable typeMap, Hashtable stringMap);
        #endregion

        #region Fixed Length String
        /// <summary>
        /// Returns the equivalent data type when a string attribute has specified size
        /// </summary>
        protected abstract object GetFixedLengthStringType();

        /// <summary>
        /// Returns the string version of equivalent data typep when a string attribute has specified size
        /// </summary>
        protected abstract string GetFixedLengthStringTypeAsString();
        #endregion

        #region To Data Type
        /// <summary>
        /// Get the data type equivalent of a .NET type
        /// </summary>
        /// <param name="map">mapping for an attribute</param>
        public object GetDataAttributeType(AttributeMap map)
        {
            Type objectType = map.ObjectAttributeType;
            Hashtable typeMap = this.TypeMap;
            object result = null;

            if ((map.Size > 0) && (objectType == typeof(string)))
            {
                result = GetFixedLengthStringType();
            }
            else
            {//size not specified               

                //handle special type cases
                if (map.IsSpecialType)
                {
                    if (map.IsEnum) objectType = typeof(int);
                    else if (map.IsArray) objectType = typeof(string);
                    else if (map.IsList) objectType = typeof(string);
                }

                //if already in map, use type specified in map
                if (typeMap.Contains(objectType)) result = typeMap[objectType];
                else
                {
                    //can't find a map, throw exception
                    TypeNotSupportedException.Publish(objectType);
                    //DataExceptionBase error = DataExceptionBase.Create(DataExceptionConstants.TypeNotSupported, typeof(Thn.Data.Exceptions.DataExceptionBase), null, objectType);

                    //if (DataTierSettings.AutoPublishError) Log.Error(error);
                    //if (!DataTierSettings.SilentError) throw (error);
                }
            }//size not specified

            return result;
        }
        #endregion

        #region Get Data Attribute AsString
        /// <summary>
        /// Gets the string version of data type equivalent to a .NET type
        /// </summary>
        /// <param name="map">mapping for an attribute</param>
        public string GetDataAttributeAsString(AttributeMap map)
        {
            string result = "";
            Type objectType = map.ObjectAttributeType;
            Hashtable stringMap = this.StringMap;

            if ((map.Size > 0) && (objectType == typeof(string)))
            {
                result = GetFixedLengthStringTypeAsString();
            }
            else
            {//size not specified

                //handle special type cases
                if (map.IsSpecialType)
                {
                    if (map.IsEnum) objectType = typeof(int);
                    else if (map.IsArray) objectType = typeof(string);
                    else if (map.IsList) objectType = typeof(string);
                }
                else 
                {
                    //this type does not have its own converter, try to change type it
                    TypeConverter con = TypeDescriptor.GetConverter(map.ObjectAttributeType);

                    //if (con is TypeConverter)
                    if (con == null || con.GetType() == typeof(System.ComponentModel.TypeConverter) ||
                        con.GetType() == typeof(System.ComponentModel.ReferenceConverter))
                    {
                        objectType = typeof(string);
                    }

                }
                //use string specified in map
                if (stringMap.Contains(objectType)) result = (string)stringMap[objectType];
                else
                {
                    //can't find a map, throw exception
                    TypeNotSupportedException.Publish(objectType);
                    //DataExceptionBase error = DataExceptionBase.Create(DataExceptionConstants.TypeNotSupported, typeof(DataExceptionBase), null, objectType);

                    //if (DataTierSettings.AutoPublishError) Log.Error(error);
                    //if (!DataTierSettings.SilentError) throw (error);
                }
            }//size not specified

            return result;
        }
        #endregion

        #region Support Multi-Command
        /// <summary>
        /// Whether this database variant accepts multiple query commands at once
        /// </summary>
        protected bool mSupportMultipleCommands = false;

        /// <summary>
        /// Checks whether this database variant accepts multiple query commands at once
        /// </summary>
        public bool SupportsMultipleCommands
        { get { return mSupportMultipleCommands; } }
        #endregion

        #region SqlStrings
        /// <summary>
        /// Contains the sql literal strings specific to current dialect
        /// </summary>
        protected SqlDialectStrings mSqlStrings = new SqlDialectStrings();

        /// <summary>
        /// Gets Sql string constants specific to this dialect
        /// </summary>
        public SqlDialectStrings SqlStrings
        { get { return mSqlStrings; } }
#endregion

        #region Parse Exception
        /// <summary>
        /// Parse a database specific exception to standard one (known to this data layer)
        /// </summary>
        /// <param name="error">original exception</param>
        /// <returns>standardized exception</returns>
        protected abstract DataExceptionBase OnParseException(Exception error);

        /// <summary>
        /// Parse a database specific exception to standard one (known to this data layer)
        /// </summary>
        /// <param name="error">original exception</param>
        /// <returns>standardized exception</returns>
        public DataExceptionBase ParseException(Exception error)
        {
            return OnParseException(error);
        }
        #endregion
    }
}

